<template>
  <div>
    <div class="cardmessage">
      <a-row style="padding-top:10vh;margin-bottom: 20px;">
        <a-col :xs="{ span : 24 }" :sm="{ span:6 }" class="formGroupTitle">确认提现信息</a-col>
      </a-row>
      <div style="padding-top: 10px">
        <a-form-item  label="银行卡信息" v-bind="formItemLayout">
          <div class="cardmsg">
            {{seat.bankCardDTO.accountName}}
            <br />
            {{seat.bankCardDTO.bankName}}（{{seat.bankCardDTO.cardNo | cardNofilter}}）
          </div>
        </a-form-item>

        <a-form-item label="提现金额" v-bind="formItemLayout">
          <div class="cardmsg">
            <span 
              style="color: #279e71;font-size:18px;font-weight: bolder;"
            >{{seat.cashWithdrawal | cashWithdrawalfilter}}</span>&ensp;元
            <span 
              style="color:#3494cd;font-size:12px;"
            >&ensp;&ensp;(额外扣除提现手续费{{serviceCharge}}元/笔)</span>
          </div>
        </a-form-item>

        <a-form-item label="支付密码" v-bind="formItemLayout">
          <div id="paypwd">
            <a-input
              style="width: 250px; margin-right: 10px"
              v-if="sensitive == 1"
              placeholder="支付密码"
              type="password"
              v-model="userpw"
              @focus="showKeyboard()"
              :maxLength="maxLength"
              @change="setInput"
            />
            <vue-pay-pwd v-else :isCursor="isCursor" :pwdWidth="250" :pwdHeight="38" :getPassword="payPw"></vue-pay-pwd>&ensp;&ensp;
            <div>
              <router-link
                style="font-size:14px;color: #156ec1;"
                to="/per/safeset/modifypayindex"
              >忘记密码？</router-link>
            </div>
          </div>
        </a-form-item>
        <div style="width: 400px; margin-left: 22vw; margin-top: -20px">
          <SimpleKeyboard
            @onChange="onChange"
            :input="input"
            v-show="isKeyBoard"
          />
        </div>
      </div>
      <a-form :form="cashform" @submit="handleSubmit">
        <div class="cardpwd">
          <div v-if="phoneVerify">
            <a-row>
              <a-col
                :xs="{ span : 24 }"
                :sm="{ span:17,offset:7 }"
                style="text-align: left;margin-bottom: 15px;"
              ></a-col>
            </a-row>
            <a-form-item label="手机号" v-bind="formItemLayout">
              <div style="text-align: left;">
                {{seat.mobile | mobileNofilters}}
                <a-button
                  style="margin-left: 20px;color:#279e71;border-color:#279e71;font-size: 14px;"
                  @click="sendcode"
                  v-if="issend"
                >发送验证码</a-button>
                <a-button
                  style="margin-left: 20px;"
                  v-if="!issend"
                  disabled
                  type="primary"
                >{{ count }}s后可再次发送</a-button>
              </div>
            </a-form-item>
            <a-form-item label="验证码" :label-col="{ span: 6 }" :wrapper-col="{ span: 6,offset:1 }">
              <a-input
                v-decorator="[
                      'usercode',
                      { rules: [{
                    required: true,
                    whitespace: true,
                    message: '请输入验证码' },{validator: validateCode}],
                    validateTrigger: 'blur'
                    }
                ]"
                size="large"
                placeholder="请输入验证码"
              ></a-input>
            </a-form-item>
          </div>
          <div></div>
        </div>
        <a-row>
          <a-col :xs="{ span : 24 }" :sm="{ span:12,offset:7 }">
            <div class="next-ok">
              <a-button type="primary" :loading="loading" html-type="submit">确认提现</a-button>
              <div style="margin-left: 15px;">
                <router-link style="color:#156ec1;" to="/marketCashOut">返回修改</router-link>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </div>
</template>

<script>
import api from "@/common/api";
import Vue from "vue";
import { JSEncrypt } from "jsencrypt";
import vuePayPwd from "vue-pay-pwd";
import SimpleKeyboard from "../common/keyboard.vue";
export default {
  components:{
    SimpleKeyboard
  },
  data() {
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18, offset: 1 },
          md: { span: 10, offset: 1 }
        }
      },
      seat: "",
      amountSum: "",
      loading: false,
      phoneVerify: false,
      phonenum: "",
      cardusername: "",
      cardname: "",
      cardid: "",
      cashform: this.$form.createForm(this),
      issend: true,
      userpw: "",
      isCursor: true, //是否开启光标
      count: 30,
      codeMsg: "获取验证码",
      timer: "",
      buttonStyle: {
        background: "#279e71"
      },
      serviceCharge: "",
      status:"",
      input: "",
      maxLength: 0,
      isKeyBoard: false,
      sensitive: localStorage.getItem("sensitive"),
    };
  },
  filters: {
    cardNofilter(value) {
      if (value) {
        var reg = /.*(.{4})$/;
        return value.replace(reg, "**** **** **** ***$1");
      }
    },
    mobileNofilters(value) {
      if (value) {
        var reg = /^(\d{3})\d{4}(\d{4})$/;
        return value.replace(reg, "$1****$2");
      }
    },
    cashWithdrawalfilter(value) {
      return parseFloat(value / 100).toFixed(2);
    }
  },
  created() {
    this.getParams();
  },
  mounted() {
    // this.selectData();
  },
  methods: {
    onChange(input) {
      console.log("input", input);
      this.userpw = input;
      this.input = input;
    },
    setInput(e) {
      console.log(e.target.value);
      this.input = e.target.value;
    },
    onKeyPress(button) {
      console.log("button", button);
    },
    showKeyboard() {
      this.isKeyBoard = true;
    },
    payPw(pw) {
      console.log("获取支付密码", pw);
      this.userpw = pw;
    },
    validateCode(rule, value, callback) {
      // let reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
      if (value && !/^[0-9]*[1-9][0-9]*$/.test(value)) {
        /* eslint-disable-next-line */
        this.amountt = false;
        callback("请输入数字");
        return;
      } else {
        //console.log(value);
        callback();
      }
    },
    handleSubmit(e) {
      e.preventDefault();
      if (!this.userpw) {
        this.$message.warning("请输入密码！");
        return
      } else {
        if (this.userpw.length < 6) {
          this.$message.warning("请输入正确密码！");
          return
        }
      }
      this.cashform.validateFields((err, values) => {
        if (!err) {
          console.log(this.seat.bankCardDTO);
          var usermobileNo = this.seat.bankCardDTO.accountNo;
          var params = { scope: "withdrawal", key: usermobileNo };

           this.loading = true
          api.fetchPubKey(
            params,
            res => {
              var pass = this.userpw;
            
              pass = api.getEncryptData(res.data.pubKey, pass);
    
              this.$axios
                .post("/agent/withdraw/market/toWithdrawal", {
                  amount: this.seat.cashWithdrawal,
                  accountNo: this.seat.bankCardDTO.accountNo,
                  mobileNo: this.seat.mobile,
                  code: values.usercode,
                  payPassword: pass,
                  key: usermobileNo
                })
                .then(res => {
                   this.loading = false
                 
                  if (res.data.code == "OK") {
                    this.$router.push({
                      name: "提现完成",
                      params: {
                        amount: this.seat.cashWithdrawal,
                        market:"market"
                      }
                    });
                  } else if(res.data.code == "LIMIT_FAIL"){
                    // let messagelist = res.data.message.split("限额:")

                    // let message = messagelist[0] + "限额:" + Number(messagelist[1])/100 + "元"

                    // this.$message.error(message);
                    this.$message.error(res.data.message);
                  }else if (res.data.message == "支付密码有误,请重新输入") {
                    console.log('flag',1)
                    let count = localStorage.getItem("failCount");
                    if (count) {
                      if(count==4){
                        this.$message.error('密码输入错误五次，请重新登陆');
                        setTimeout(()=>{
                          this.$router.push({path:'/'})
                        },1500)
                      }else{
                        this.$message.error(res.data.message);
                        localStorage.setItem('failCount',parseInt(count)+1) 
                      }
                    }else{
                      localStorage.setItem('failCount',1)
                      this.$message.error(res.data.message);
                    }
                  }else{
                    this.$message.error(res.data.message);
                  }
                });
            },
            error => {
              alert("错误");
            }
          );
        }
      });
    },
    getParams() {
      // 取到路由带过来的参数
      this.seat = this.$route.params.seat;
      // this.amountSum = Number(this.$route.params.amountSum) / 100;
      this.serviceCharge = Number(this.seat.serviceCharge) / 100;

      if (this.seat.sendSms == true) {
        this.phoneVerify = true;
      } else {
        this.phoneVerify = false;
      }
    },

    sendcode() {
      const TIME_COUNT = 30;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.issend = false;
        this.$axios
          .get("/agent/sms/send/" + this.seat.mobile)
          .then(res => {
            console.log(res);
            if(res.data.code == "OK"){

            }else{
              this.$message.warning(res.data.message)
            }
          });
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.issend = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    }
  }
};
</script>

<style scoped>
.top {
  height: 50px;
}

.cardmessage {
  font-size: 16px;
}

.cardmsg {
  text-align: left;
}

#paypwd {
  display: flex;
  flex-direction: row;
}

.next-ok {
  padding-top: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.formGroupTitle {
  font-size: 20px;
  font-weight: 600;
  text-align: right;
}
</style>